<?php

//namespace app\admin\lib\weixin;
namespace app\admin\controller;
use think\Controller;

/**
 * 微信服务商 - 添加分账接收方
 * Class Weixin
 * @package app\admin\lib\weixin
 */
class Weixin9782 extends Controller
{
    private $addsep_receiving_url;              // 添加分账接收方请求URL
    private $addsep_receiving_type;             // 分账接收方类型 此处是个人openid类型
    private $addsep_receiving_relation_type;    // 分账关系类型
    private $mch_id;                            // 服务商父商户号
    private $appid;                             // 公众号appid
    private $mch_secrect;                       // 此处是商户key！！！

    function __construct()
    {
        $this->addsep_receiving_url = 'https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver';
        $this->addsep_receiving_type = 'PERSONAL_OPENID';
        $this->addsep_receiving_relation_type = 'PARTNER';
        $this->mch_id = '1620905287';
        $this->appid = 'wx1116df9b94b6bd93';
        $this->mch_secrect = 'uc0kxqezvhwwmo2fqrvlqnz15dwh04yf';
    }
/*
    [return_code] => SUCCESS
    [result_code] => SUCCESS
    [mch_id] => 1609549160
    [appid] => wx1116df9b94b6bd93
    [nonce_str] => c86b86685a2cc9f5
    [sign] => DCEB4B9A6D6F8EBC0A088D6416DD39426EE0056F275C77F82734FB7F44732DE9
    [transaction_id] => 4200001391202204204534332521
    [out_order_no] => 886387_gift_YsK5526
    [order_id] => 30001708622022042029520304946
    [receivers] => [{"type":"PERSONAL_OPENID","account":"ogpbF4pwxjhFlX7WGGSqGwoQY5Mo","amount":3,"description":"代理分润","result":"PENDING","finish_time":"19700101080000","detail_id":"36001708622022042039293036663"},{"type":"MERCHANT_ID","account":"1609549160","amount":7,"description":"解冻给分账方","result":"PENDING","finish_time":"19700101080000","detail_id":"36001708622022042039293036664"}]
    [status] => PROCESSING
*/
    public function profitsharingquery()
    {
        $this->mch_id = '1571615431';
        $this->appid = $appid;
        $mch_secrect = '16893E36DD2DF093513B508FBBCF3BF6';
        $tmp_receiving_data = [
            'mch_id' => '1571615431',
            'nonce_str' => $this->get_nonce_str(),
            'sign_type' => 'HMAC-SHA256',
            'transaction_id' => '4200001622202209016543439061',
            'out_order_no' => '1575735_gift_Wnzzwnu',

        ];
        $tmp_receiving_data['sign'] = $this->make_sign($tmp_receiving_data,$mch_secrect);
        $xml = $this->array_to_xml($tmp_receiving_data);
        
        $do_arr = $this->post_xml_curl($xml, 'https://api.mch.weixin.qq.com/pay/profitsharingquery', 30, true);
        $result = $this->xml_to_array($do_arr);
print_r($result);exit;
        return $result;
            
    }
    
    //请求分账
    public function profitsharing($mch_id,$appid,$transaction_id,$out_order_no,$openid,$amount,$mch_secrect)
    {
        $this->mch_id = $mch_id;
        $this->appid = $appid;
        $this->mch_secrect = $mch_secrect;
        $tmp_receiving_data = [
            'mch_id' => $mch_id,
            //'sub_mch_id' => $sub_mch_id,        // 微信支付分配的子商户号
            'appid' => $appid,
            //'sub_appid' => $sub_appid,          // 微信分配的子商户公众账号ID
            'nonce_str' => $this->get_nonce_str(),
            'sign_type' => 'HMAC-SHA256',
            //'receiver' => $this->receiver('ogpbF4pwxjhFlX7WGGSqGwoQY5Mo'),
            'transaction_id' => $transaction_id,
            'out_order_no' => $out_order_no,
            'receivers'=> json_encode([
                    'type'=>'PERSONAL_OPENID',
                    'account'=>$openid,
                    'amount'=>$amount,
                    'description'=>'代理分润',
                ])
        ];
        $tmp_receiving_data['sign'] = $this->make_sign($tmp_receiving_data,$mch_secrect);
        $xml = $this->array_to_xml($tmp_receiving_data);
        
        $do_arr = $this->post_xml_curl($xml, 'https://api.mch.weixin.qq.com/secapi/pay/profitsharing', 30, true);
        $result = $this->xml_to_array($do_arr);

        return $result;
            
    }
    
    public function fwsProfitsharing($mch_id,$appid,$transaction_id,$out_order_no,$openid,$amount,$mch_secrect)
    {
        
        $this->mch_id = '1626666963';
        $this->appid = 'wxb20b1e85d5491f07';
        $this->mch_secrect = $mch_secrect;
        $tmp_receiving_data = [
            'mch_id' => '1626666963',
            'sub_mch_id' => $mch_id,        // 微信支付分配的子商户号
            'appid' => 'wxb20b1e85d5491f07',
            'sub_appid' => $appid,          // 微信分配的子商户公众账号ID
            'nonce_str' => $this->get_nonce_str(),
            'sign_type' => 'HMAC-SHA256',
            //'receiver' => $this->receiver('ogpbF4pwxjhFlX7WGGSqGwoQY5Mo'),
            'transaction_id' => $transaction_id,
            'out_order_no' => $out_order_no,
            'receivers'=> json_encode([
                [
                    'type'=>'PERSONAL_SUB_OPENID',
                    'account'=>$openid,
                    'amount'=>$amount,
                    'description'=>'代理分润',
                ],
                ])
        ];
        
        $tmp_receiving_data['sign'] = $this->make_sign($tmp_receiving_data,$mch_secrect);
        $xml = $this->array_to_xml($tmp_receiving_data);
        $do_arr = $this->post_xml_curl($xml, 'https://api.mch.weixin.qq.com/secapi/pay/profitsharing', 30, true);

        $result = $this->xml_to_array($do_arr);
        
        return $result;
            
    }
    
    
    
    public function profitsharingquery11()
    {
        $tmp_receiving_data = [
            'mch_id' => $this->mch_id,
            'nonce_str' => $this->get_nonce_str(),
            'sign_type' => 'HMAC-SHA256',
            'transaction_id' => '4200001385202204224985723880',
            'out_order_no' => '891027_gift_a66jCx8',
        ];
        
        $tmp_receiving_data['sign'] = $this->make_sign($tmp_receiving_data,$this->mch_secrect);
        $xml = $this->array_to_xml($tmp_receiving_data);
        $do_arr = $this->post_xml_curl($xml, 'https://api.mch.weixin.qq.com/pay/profitsharingquery', 30);
        $result = $this->xml_to_array($do_arr);
        print_r($result);
    }
    

    /**
     * Notes: 接收方信息
     * @param $openid
     * @return false|string
     */
    private function receiver($openid)
    {
        $tmp_receiver_arr = [
            'type' => 'PERSONAL_OPENID',
            'account' => $openid,
            'relation_type' => $this->addsep_receiving_relation_type,
        ];

        return json_encode($tmp_receiver_arr);
    }

    /**
     * Notes: 获取随机数
     * @param int $length
     * @return string
     */
    private function get_nonce_str($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * Notes: 生成sign
     * @param $arr
     * @param $secret
     * @return string
     */
    private function make_sign($arr, $secret)
    {
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $str = $this->to_url_params($arr);
        //签名步骤二：在str后加入KEY
        $str = $str . "&key=" . $secret;
        //签名步骤三：HMAC-SHA256 类型  加密的字符串 key是商户秘钥
        $str = hash_hmac('sha256', $str, $secret);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($str);
        return $result;
    }

    /**
     * Notes: 数组转字符串
     * @param $arr
     * @return string
     */
    private function to_url_params($arr)
    {
        $str = "";
        foreach ($arr as $k => $v) {
            if (!empty($v) && ($k != 'sign')) {
                $str .= "$k" . "=" . $v . "&";
            }
        }
        $str = rtrim($str, "&");
        return $str;
    }

    /**
     * Notes: 数组转XML
     * @param $arr
     * @return string
     */
    private function array_to_xml($arr){
        $xml = '<?xml version="1.0" encoding="UTF-8"?><xml>';
        foreach ($arr as $key => $val) {
            $xml.="<".$key.">$val</".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     * Notes: XML转数组
     * @param $xml
     * @return mixed
     */
    private function xml_to_array($xml){
        libxml_disable_entity_loader(true);
        $arr= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }

    /**
     * Notes: POST 请求 此处不需要证书
     * @param $xml
     * @param $url
     * @param int $second
     * @return bool|string
     */
    private function post_xml_curl($xml, $url, $second = 30, $useCert = FALSE){
        //初始化curl
        //echo file_get_contents('/www/wwwroot/oa.com/uploads/1609549160/apiclient_cert.pem');
        
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        if($useCert)
        {
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
		    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, '/www/wwwroot/oa.com/cert123561235165/'.$this->mch_id.'/apiclient_cert.pem');
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, '/www/wwwroot/oa.com/cert123561235165/'.$this->mch_id.'/apiclient_key.pem');
        }
        else
        {
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        }
        
        //运行curl
        $data = curl_exec($ch);
        //curl_close($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

}